package com.lcc.lynx.security.interceptor;

import com.lcc.lynx.common.cache.enums.CacheEnum;
import com.lcc.lynx.common.cache.service.CacheService;
import com.lcc.lynx.common.exception.BusinessException;
import com.lcc.lynx.common.utils.MD5;
import com.lcc.lynx.security.ThreadVariable;
import com.lcc.lynx.security.annotation.RepeatSubmit;
import com.lcc.lynx.security.wrapper.RepeatedlyRequestWrapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 重复提交拦截器
 * @author lcc
 * @date 2022/11/15
 */
@Component
public class RepeatSubmitInterceptor implements HandlerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(RepeatSubmitInterceptor.class);

    @Autowired
    private CacheService cacheService;

    private final String SUBMIT_KEY = "submit-key";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse resp, Object handler) throws Exception {
        if(handler instanceof HandlerMethod method){
            RepeatSubmit annotation = method.getMethodAnnotation(RepeatSubmit.class);
            if(annotation == null){
                return true;
            }
            String key = CacheEnum.lock + getKey(request);
            request.setAttribute(SUBMIT_KEY, key);

            synchronized (RepeatSubmitInterceptor.class){
                if(cacheService.contains(key)){
                    throw new BusinessException(annotation.message());
                }
                cacheService.set(key, "", annotation.interval(), TimeUnit.MILLISECONDS);
            }
        }
        return true;
    }

    public String getKey(HttpServletRequest request) throws IOException {
        String url = request.getRequestURI();
        String token = ThreadVariable.localToken.get();
        String body = "body";
        if(request instanceof RepeatedlyRequestWrapper requestWrapper){
            body = requestWrapper.getBody();
        }
        String content = url + body + token;
        return MD5.encrypt(content.getBytes());
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
        Object key = request.getAttribute(SUBMIT_KEY);
        if(key != null){
            cacheService.del(key.toString());
        }
    }
}
